# -*- coding:utf-8-*-
# 14.3.2 延迟提交数据
import urllib.request
import urllib.parse
import json
import time

url = "http://fanyi.youdao.com/translate?smartresult = dict&smartresult=rule&smartresult=" \
      "ugc&sessionFrom = http://www.youdao.com/"
while True:
    content = input('请输入待翻译内容（输入“q!”退出程序）：')
    if content == 'q!':
        break
    data = {}
    data['type'] = 'AUTO'
    data['i'] = content
    data['doctype'] = 'json'
    data['xmlVersion'] = '1.6'
    data['keyfrom'] = 'fanyi.web'
    data['ue'] = 'UTF-8'
    data['typeResult'] = 'true'
    data = urllib.parse.urlencode(data).encode('utf-8')
    req = urllib.request.urlopen(url, data)
    req.add_header('Referer', 'http://fanyi.youdao.com')
    req.add_header('User-Agent', 'Mozilia/5.0(Macintosh;Intel Mac OS X 10_10_1) AppleWebKit/537.36(KHTML,like Gecko)' \
                                 'Chrome/39.0.2171.95 Safari/537.36X-Requested-With:XMLHttpRequest')
    response = urllib.request.urlopen(url, data)
    html = response.read().decode('utf-8')
    # 编码问题：http://bbs.fishc.com/thread-56452-1-1.html
    target = json.loads(html)  # 解析JSON格式字符串
    # type(target)
    print("翻译结果是：%s" % (target['translateResult'][0][0]['tgt']))
    time.sleep(5)
